package net.jqsoft.common.lang;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 字符串工具类
 * </p>
 * 
 *
 */
public class StringTools {

	/**
	 * UTF-8 编码格式
	 */
	public static final String UTF8 = "UTF-8";

	/**
	 * 空字符
	 */
	public static final String EMPTY = "";

	/**
	 * 占位符
	 */
	public static final String PLACE_HOLDER = "{%s}";

	/**
	 * 分隔符
	 */
	public static final String SEPARATOR = ",";

	
	public static String getUUID() {
		return UUID.randomUUID().toString().replace("-", "");
	}

	public static String convert(final Object object) {
		if (null == object)
			return null;
		return String.valueOf(object);
	}

	public static boolean isEmpty(final String string) {
		return string == null || string.isEmpty();
	}

	public static boolean notEmpty(final String string) {
		return !isEmpty(string);
	}

	/**
	 * <p>
	 * 判断字符串是否为纯大写字母
	 * </p>
	 *
	 * @param str
	 *            要匹配的字符串
	 * @return
	 */
	public static boolean isUpperCase(String str) {
		return match("^[A-Z]+$", str);
	}

	/**
	 * <p>
	 * 正则表达式匹配
	 * </p>
	 *
	 * @param regex
	 *            正则表达式字符串
	 * @param str
	 *            要匹配的字符串
	 * @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
	 */
	public static boolean match(String regex, String str) {
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(str);
		return matcher.matches();
	}

	public static List<String> split(final String str) {
		if (null == str || "".equals(str))
			return Collections.EMPTY_LIST;
		return Arrays.asList(str.split(SEPARATOR));
	}

	public static List<String> split(final String str, final String separatorChars) {
		if (null == str || "".equals(str))
			return Collections.EMPTY_LIST;
		return Arrays.asList(str.split(separatorChars));
	}

	public static String join(final Collection<String> collection) {
		StringBuilder sb = new StringBuilder();
		for (String str : collection) {
			if (sb.length() > 0)
				sb.append(SEPARATOR);
			sb.append(str);
		}
		return sb.toString();
	}

	public static String join(final Collection<String> collection, final String separatorChars) {
		StringBuilder sb = new StringBuilder();
		for (String str : collection) {
			if (sb.length() > 0)
				sb.append(separatorChars);
			sb.append(str);
		}
		return sb.toString();
	}
}